var MongoClient = require('mongodb').MongoClient;
var express = require("express");
var fs = require("fs");
var bodyParser = require('body-parser');
var multer  = require('multer');
var app = express();

// static files
app.use(express.static('public'));

app.use(express.static(__dirname + '/up')); //静态文件目录

app.use(multer({ dest: '/tmp/'}).array('image'));

// use bodyParser-json
app.use(bodyParser.json());
// use bodyParser-text
app.use(bodyParser.text({type:"txt"}));

app.use(bodyParser.urlencoded({ extended: true }));

function Create(collection, object) {
    collection.insert(object, function (err, result) {

    });
}

// params example 1 
app.get('/find/:id', function(req,res){
	console.log(req.params.id);
	res.send("success");
});

// params example 2
app.get('/find/:group/:name', function(req, res) {
	console.log(req.params.group+" "+req.params.name);
	res.send(req.params.group+" "+req.params.name);
});

// query example 1
app.get('/search', function(req, res){
	console.log(req.query.id);
	console.log(req.query.name);
	res.send(req.query.id+" "+req.query.name)
});

// get
app.get('/', function(req, res){
    console.log('request.url:',req.url);  //打印请求的地址
	res.setHeader("Access-Control-Allow-Origin", "*");//跨域访问
    console.log(req.query); //打印参数数据
    
    var obj = { "username":req.query.username , "password":req.query.password, "site":"www.11111.com"};
    var myJSON = JSON.stringify(obj);
    res.end(myJSON);
});

// add 
app.get('/add', function(req, res) {
    console.log('request.url:',req.url);  //打印请求的地址
	res.setHeader("Access-Control-Allow-Origin", "*");//跨域访问
    console.log(req.query);
    var obj = { "username":req.query.username , "password":req.query.password, "site":"www.11111.com"};
    var myJSON = JSON.stringify(obj);
    res.end(myJSON);
});

//登录
app.get("/login", function (req, res) {
    console.log('request.url:',req.url);  //打印请求的地址
    res.setHeader("Access-Control-Allow-Origin", "*");//跨域访问
    console.log(req.query); //打印参数数据

    MongoClient.connect("mongodb://localhost", function (err, db) {
        var MyDB = db.db("userDB");

        MyDB.collection("users", function (err, users) {
            users.findOne({username:req.query.username}, function (err, item) {
                if (!item) {
                    db.close();
                    var obj = { value: "false", text:"Users do not exist!"};
                    var myJSON = JSON.stringify(obj);
                    res.end(myJSON);
                } else {
                    console.log('find success!');

                    if (item.password === req.query.password) {
                        db.close();
                        var obj = { value: "true", usertype: item.usertype, text:"User name and password verification is successful!"};
                        var myJSON = JSON.stringify(obj);
                        res.end(myJSON);
                    }
                    else {
                        db.close();
                        var obj = { value: "false", text:"Wrong password!"};
                        var myJSON = JSON.stringify(obj);
                        res.end(myJSON);
                    }
                }
            });
        });
    });
});

//注册
app.get("/register", function (req, res) {
    console.log('request.url:',req.url);  //打印请求的地址
    res.setHeader("Access-Control-Allow-Origin", "*");//跨域访问
    console.log(req.query); //打印参数数据

    MongoClient.connect("mongodb://localhost", function (err, db) {
        var MyDB = db.db("userDB");

        MyDB.collection("users", function (err, users) {
            users.findOne({username:req.query.username}, function (err, item) {
                if (!item) {
                    MyDB.createCollection("users", function (err, users) {
                        Create(users, {username: req.query.username, password: req.query.password, real_name: req.query.real_name, phone_number: req.query.phone_number, bank_card_number: req.query.bank_card_number, usertype: req.query.usertype,});
                        db.close();
                        var obj = { value: "true", text:"Create user success!"};
                        var myJSON = JSON.stringify(obj);
                        res.end(myJSON);
                    });
                } else {
                    db.close();
                    var obj = { value: "false", text:"User name already exists!"};
                    var myJSON = JSON.stringify(obj);
                    res.end(myJSON);
                }
            });
        });
    });
});

//商品删除
app.get("/product_delete", function (req, res) {
    console.log('request.url:',req.url);  //打印请求的地址
    res.setHeader("Access-Control-Allow-Origin", "*");//跨域访问
    console.log(req.query); //打印参数数据

    MongoClient.connect("mongodb://localhost", function (err, db) {
        var MyDB = db.db("userDB");
        var whereStr = {"name":req.query.product_name};  // 查询条件
        MyDB.collection("products").deleteOne(whereStr, function(err, result) {
            if (err) {
                var obj = { value: "false", text:err};
                var myJSON = JSON.stringify(obj);
                res.end(myJSON);
            }
            else {
                var obj = { value: "true", text:"删除成功"};
                var myJSON = JSON.stringify(obj);
                res.end(myJSON);
            }
            db.close();
        });
    });
});

//商品定价修改
app.get("/product_cost_change", function (req, res) {
    console.log('request.url:',req.url);  //打印请求的地址
    res.setHeader("Access-Control-Allow-Origin", "*");//跨域访问
    console.log(req.query); //打印参数数据

    MongoClient.connect("mongodb://localhost", function (err, db) {
        var MyDB = db.db("userDB");
        var whereStr = {"name":req.query.product_name};  // 查询条件
        var updateStr = {$set: { "cost" : req.query.new_cost }};//更新数据
        MyDB.collection("products").updateOne(whereStr, updateStr, function(err, result) {
            if (err) {
                var obj = { value: "false", text:err};
                var myJSON = JSON.stringify(obj);
                res.end(myJSON);
            }
            else {
                var obj = { value: "true", text:"更新成功"};
                var myJSON = JSON.stringify(obj);
                res.end(myJSON);
            }
            db.close();
        });
    });
});



//商品展示
app.get("/product_display", function (req, res) {
    console.log('request.url:',req.url);  //打印请求的地址
    res.setHeader("Access-Control-Allow-Origin", "*");//跨域访问
    console.log(req.query); //打印参数数据

    MongoClient.connect("mongodb://localhost", function (err, db) {
        var MyDB = db.db("userDB");
        MyDB.collection("products").find({}).toArray(function(err,result){
            if (err) throw err;
            console.log(result);
            for (var i=0, l=result.length; i<l; i++)
            {
                let bitmap = fs.readFileSync(result[i].picture);
                result[i].picture ='data:image/jpeg;base64,'+ new Buffer(bitmap).toString('base64');
            }
            var myJSON = JSON.stringify(result);
            res.end(myJSON);
            db.close();
        });
    });
});


//图片上传
app.post('/upload',function(req,res) {
    console.log('request.url:',req.url);  //打印请求的地址
    res.setHeader("Access-Control-Allow-Origin", "*");//跨域访问

    console.log(req.body);
    var obj =JSON.parse(req.body);

    MongoClient.connect("mongodb://localhost", function (err, db) {
        var MyDB = db.db("userDB");

        MyDB.collection("products", function (err, users) {
            users.findOne({name:obj.product_name}, function (err, item) {//判断商品是否重名
                if (item) {
                    db.close();
                    var return_obj = { value: "false", text:"User name already exists!"};
                    var myJSON = JSON.stringify(return_obj);
                    res.end(myJSON);
                } else {//保存图片
                    var imgData = obj.img_data;
                    //过滤data:URL
                    var base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
                    var dataBuffer = new Buffer(base64Data, 'base64');
                    fs.writeFile("src/photo/" +obj.product_name+ ".png", dataBuffer, function(err) {
                        if(err){
                            var return_obj = { value: "false", text:"上传图片失败"};
                            var myJSON = JSON.stringify(return_obj);
                            res.end(myJSON);
                        }else{//图片保存成功
                        }
                    });
                    //数据库写记录
                    MyDB.createCollection("products", function (err, users) {
                        Create(users, {
                            name: obj.product_name,
                            cost: obj.product_cost,
                            describe: obj.product_describe,
                            picture: "src/photo/" +obj.product_name+ ".png"
                        });
                        db.close();
                        var return_obj = { value: "true", text:"上架商品成功"};
                        var myJSON = JSON.stringify(return_obj);
                        res.end(myJSON);
                    });
                }
            });
        });
    });
});


// json
app.post("/json", function(req, res){
	console.log(req.body)
});

// text text
app.post("/text", function(req, res){
	console.log(req.body)
});

// create server listening at 3000
var server = app.listen(3000, function(){
	console.log("App listening at 3000...")
});
